import { Component, ViewChild, Input } from '@angular/core';
import { Events, AlertController, App, ModalController, NavController, Content } from 'ionic-angular';
import { TodoService } from './todo.service';
import { Storage } from '@ionic/storage';
import { Config } from '../../providers/config';
import { DomSanitizer } from '@angular/platform-browser';
import { EmailDetailPage } from '../email/detail/detail.component';
import { TaskDetailPage } from '../task/detail/detail.component';
import { TaskListService } from '../task/list/list.service';
import { InfoDetailPage } from '../../pages/info/detail/detail.component';
import _ from 'lodash';
import { DraftDetailPage } from "../draft/detail/detail.component";

import { Common } from "../../providers/common";

@Component({
  selector: 'todo-page',
  templateUrl: './todo.html',
  providers: [TodoService, TaskListService]
})
export class TodoPage {
  moa_page_name: any = "todo-page";
  moa_page_explain: any = "协同办公";

  // 列表数据
  listData: any = {};
  @Input() public isFromMainPage: boolean;
  @ViewChild(Content) content: Content;

  segment = 'inbox';
  // 用来记录切换之前的
  currentSegment = 'inbox';

  name = '';

  segments = [{
    name: 'inbox',
    text: '收件箱'
  }, {
    name: 'todo',
    text: '未办文件'
  }];

  constructor(
    public alertCtrl: AlertController,
    public app: App,
    public modalCtrl: ModalController,
    public navCtrl: NavController,
    public todoService: TodoService,
    public taskListService: TaskListService,
    public config: Config,
    private sanitizer: DomSanitizer,
    public events: Events,
    public storage: Storage,
    private common: Common
  ) {
    let that = this;
    this.storage.get('userInfo').then(function (userInfo) {
      if (userInfo) {
        that.name = userInfo.emname;
      }
    });
    _.each(this.segments, function (item, index) {
      that.listData[item.name] = {
        pageIndex: 1,
        data: [],
        scrollTop: 0,
        isLoadMore: true
      };
    });

    this.events.unsubscribe('email-list:delete');
    // 监听是否有删除邮件操作
    this.events.subscribe('email-list:delete', (deletedId) => {
      // user and time are the same arguments passed in `events.publish(user, time)`
      console.info('----- todo -email-list:delete------');
      console.info(deletedId);
      _.remove(this.listData[this.segment].data, {
        mailbosid: deletedId
      })
    });

    this.events.unsubscribe("task-detail:todo,deal has updated");
    this.events.unsubscribe("task-detail: take back-todo"); // 收回
    // 启动监听，流程有更新操作，刷新未办列表
    this.events.subscribe("task-detail:todo,deal has updated", data => {
      console.log("###监听到task-detail:todo,deal has updated:")
      _.pull(this.listData["todo"].data, _.find(this.listData["todo"].data, { "bid": data.bid }));
    });

    //启动监听，收回
    this.events.subscribe("task-detail: take back-todo", data => {
      console.log("###监听到task-detail: take back-todo:")
      this.loadListData(this.segment, 1, null, null, false);
    });

    // 初始化数据
    this.loadListData(this.segment, 1, null, null, true);

    /*this.storage.get("userInfo").then(user => {
      console.log(user);
      this.todoService.getUSPAthority(user.loginid).subscribe(data => {
        console.log(data);
        if (data) {
          if (data[0].c_allow == "1") {
            that.storage.set("indexAuthority", data[0]);
          }
        } else {
          that.storage.set("indexAuthority", null);
        }
      });

      this.todoService.getIPMAuthority().subscribe(result => {
          if (result) {
            that.storage.set("IPMAuthority", result);
          } else {
            that.storage.set("IPMAuthority", null);
          }
      });

    });*/
  }
  /**
   * [loadListData 加载列表数据]
   * @param {[type]} type           [类型]
   * @param {[type]} page           [页码]
   * @param {[type]} infiniteScroll [加载更多组件]
   * @param {[type]} refresher      [下拉刷新组件]
   */
  loadListData(type, page, infiniteScroll, refresher, isShowLoading) {
    this.todoService.getListData(page, type, isShowLoading).subscribe(data => {
      if (data) {
        if (this.segment == "inbox") {
          _.forEach(data, d => {
            d.bostitle = this.sanitizer.bypassSecurityTrustHtml(d.bostitle);
          });
        }
        console.info(data);
        // 如果加载第一页，则清空数据
        if (page == 1) {
          this.listData[type].isLoadMore = true;
          this.listData[type].data = [];
        }
        // 把现有数据和新加载的数据合并
        this.listData[type].data = _.concat(this.listData[type].data, data);
        // 增加搜索索引
        this.listData[type].pageIndex = this.listData[type].pageIndex + 1;
        // 如果返回数据少于请求页数，则不再加载更多
        if (data.length < this.config.pageSize) {
          this.listData[type].isLoadMore = false;
        }
      } else {
        this.listData[type].isLoadMore = false;
      }
      // complete event
      if (infiniteScroll) {
        infiniteScroll.complete();
      }
      if (refresher) {
        refresher.complete();
      }
    })
  };

  onSegmentChange(segmentEvent) {
    this.listData[this.currentSegment].scrollTop = this.content.scrollTop;
    if (this.listData[this.segment].pageIndex === 1) {
      this.loadListData(this.segment, 1, null, null, true);
    }
    this.content.scrollTo(0, this.listData[this.segment].scrollTop, 1);
    this.currentSegment = this.segment;

    switch (this.segment) {
      case "inbox":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "收件箱");
        break;
      case "todo":
        this.common.saveUserStatistics(this.moa_page_name, this.moa_page_name + "-" + this.segment, "未办文件");
        break;
    }

  };
  /**
   * [goDetailPage 跳转详情页]
   * @param {[type]} item [参数]
   */
  goEmailDetailPage(item) {
    console.info(item);
    item.readflag = 1;
    this.navCtrl.push(EmailDetailPage, {
      id: item.mailbosid,
      type: 'IMailInbox'
    });
  };

  /**
   * [goTaskDetailPage 跳转代办详情页面]
   * @param {[type]} item [参数]
   */
  goTaskDetailPage(item) {
    console.log(item);
    //通知公告页面针对待办和送阅的处理方式是，判断sreserved3的状态，如果sreserved3不等于5或者7，
    //那么就表示这是一个待办（未发布）；如果为5或者7，那么表示这是一个送阅（已发布）
    if (item.bomid == "t_info_Doc") {
      this.taskListService.selectAllInfo(item.bid).subscribe(data => {
        //console.log(data);
        if (_.indexOf(["5"], data.sreserved3) > -1) { // 已发布，跳转到通知公告详情页面
          this.navCtrl.push(InfoDetailPage, { fbbosid: item.bid });
        } else {
          this.navCtrl.push(TaskDetailPage, { id: item.bid, wkiType: this.listData[this.segment].wkiType, wkiState: item.wkiState });
        }
      })
    } else {
      if (this.config.allowDraftFlow.indexOf(item.bomid) > -1 && (item.wkiName === "起始节点"
        || item.wkiName.indexOf("起草") > -1)) {
        this.taskListService.selectAllInfo(item.bid).subscribe(data => {
          console.log("selectAllInfo().data", data);
          if (data && data.sreserved3) {
            if (data.sreserved3 === "" || data.sreserved3 === "8" || data.sreserved3 === "7") {
              this.goDraftEditPage(item);
            } else {
              this.navCtrl.push(TaskDetailPage, { id: item.bid, wkiType: "2", wkiState: item.wkiState });
            }
          } else {
            this.goDraftEditPage(item);
          }
        });
      } else {
        this.navCtrl.push(TaskDetailPage, { id: item.bid, wkiType: "2", wkiState: item.wkiState });
      }
    }
  }

  goDraftEditPage(item) {
    let type = "";
    switch (item.bomid) {
      case "T_HR_ChuChai":
        type = "ccsq";
        break;
      case "T_HR_ChuJingSQ":
        type = "cjsq";
        break;
      case "T_HR_ChuQinBG":
        type = "cqbg";
        break;
      case "T_HR_GongWuWC":
        type = "gwwc";
        break;
      case "T_HR_QingJia":
        type = "qxjsq";
        break;
    }

    this.navCtrl.push(DraftDetailPage, {
      ops: "reject",
      bosid: item.bid,
      type: type
    });
  }

  ionViewDidLoad() {

  };
  /**
   * [doInfinite 加载更多]
   * @param {[type]} infiniteScroll [事件]
   */
  doInfinite(infiniteScroll) {
    if (this.listData[this.segment].isLoadMore) {
      this.loadListData(this.segment, this.listData[this.segment].pageIndex, infiniteScroll, null, true);
    } else {
      infiniteScroll.complete();
    }
  }
  /**
   * [doRefresh 下拉刷新]
   * @param {[type]} refresher [事件]
   */
  doRefresh(refresher) {
    this.listData[this.segment].pageIndex = 1;
    this.listData[this.segment].isLoadMore = true;
    this.loadListData(this.segment, this.listData[this.segment].pageIndex, null, refresher, true);
  }

}
